package com.af.monitorModule.timmer;

import com.af.monitorModule.MonitorModuleApplication;
import com.af.monitorModule.generator.entity.TimedTask;
import com.af.monitorModule.generator.mapper.TimedTaskMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Component
public class OverdueTasks {

    private static final Logger logger = LoggerFactory.getLogger(OverdueTasks.class);

    @Autowired
    private TimedTaskMapper timedTaskMapper;

    @Scheduled(cron = "0 0/5 * * * ? ")
    @Transactional
    public void autoForward(){
        try{
        QueryWrapper<TimedTask> query = new QueryWrapper<>();
        query.eq("state",1);
        query.lt("task_run_time", LocalDateTime.now().plusMinutes(-3));
        List<TimedTask> timedTasks = timedTaskMapper.selectList(query);
        if (timedTasks.size() > 0){
            logger.info("有过期无法执行的任务，进行修正：\n" + timedTasks.toString());
            timedTasks.forEach( v -> {
                timedTaskMapper.updateById(v.setTaskRunTime(v.getTaskRunTime().plusHours(v.getTaskCycleHour()).plusDays(v.getTaskCycleDay())));
            });
        }
        }catch (Exception e){
            logger.error("自动清除过期定时任务失败，错误类型" + e.getMessage());
        }

    }
}
